﻿Friend Class Handler_UploadFile
    Private Shared mDaemon As Threading.Thread
    Private Shared mWorkQueue As New Generic.Queue(Of WorkItem)

    Public Shared Sub Start()
    End Sub
    Public Shared Sub [Stop]()
    End Sub

    Private Shared Sub Daemon()
        Try
            Do
                Try
                    Threading.Thread.Sleep(5000)
                Catch ex As Threading.ThreadAbortException
                    Exit Do
                Catch ex As Exception
                    Manager.OnLogException(ex)
                End Try
            Loop
        Catch ex As Threading.ThreadAbortException
        Catch ex As Exception
            Manager.OnLogException(ex)
        End Try
    End Sub

    Private Shared Function UploadQueuePath() As String
        Dim strRoot As String
        If String.IsNullOrEmpty(Settings.WorkingFolder) Then
            strRoot = IO.Path.Combine(System.IO.Path.GetTempPath, "B2B_Backup_UploadQueue")
        ElseIf IO.Directory.Exists(Settings.WorkingFolder) Then
            strRoot = IO.Path.Combine(Settings.WorkingFolder, "UploadQueue")
        Else
            strRoot = IO.Path.Combine(System.IO.Path.GetTempPath, "B2B_Backup_UploadQueue")
        End If
        If Not IO.Directory.Exists(strRoot) Then IO.Directory.CreateDirectory(strRoot)
        Return strRoot
    End Function

    Private Shared Function MoveFileToUploadQueueFolder(ByVal filePath As String) As String
        Dim strNewPath As String = IO.Path.Combine(UploadQueuePath, IO.Path.GetFileName(filePath))
        IO.File.Move(filePath, strNewPath)
        Return strNewPath
    End Function

    Public Shared Sub QueueUpload(ByVal job As Entities.Backup.Job, ByVal fileToStorePath As String, ByVal fileInfo As System.IO.FileInfo, ByVal storedVersions As Generic.List(Of Entities.Backup.StoredFile))
        fileToStorePath = MoveFileToUploadQueueFolder(fileToStorePath)
        Dim clsItem As New WorkItem
        clsItem.Job = job
        clsItem.FileInfo = fileInfo
        clsItem.FileToStorePath = fileToStorePath
        clsItem.StoredVersions = storedVersions
        SyncLock mWorkQueue
            mWorkQueue.Enqueue(clsItem)
        End SyncLock
    End Sub

    Private Shared Function GetNextWorkItem() As WorkItem
        SyncLock mWorkQueue
            If mWorkQueue.Count = 0 Then
                Return Nothing
            Else
                Return mWorkQueue.Dequeue
            End If
        End SyncLock
    End Function

    Private Class WorkItem
        Public Job As Entities.Backup.Job
        Public FileInfo As System.IO.FileInfo
        Public FileToStorePath As String
        Public StoredVersions As Generic.List(Of Entities.Backup.StoredFile)
    End Class

End Class
